package com.toycloud.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.toycloud.business.domain.DemandLog;
import com.toycloud.business.domain.DemandRecord;
import com.toycloud.business.domain.bo.DemandLogBo;
import com.toycloud.business.domain.bo.DemandRecordBo;
import com.toycloud.business.domain.vo.DemandLogVo;
import com.toycloud.business.domain.vo.DemandRecordVo;
import com.toycloud.business.dto.results.UserParam;
import com.toycloud.business.service.IDemandLogService;
import com.toycloud.common.core.utils.DateUtils;
import com.toycloud.common.sso.api.RemoteSsoService;
import com.toycloud.common.utils.StringUtils;
import com.toycloud.common.core.page.TableDataInfo;
import com.toycloud.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.toycloud.system.mapper.demand.DemandLogMapper;
import com.toycloud.system.mapper.demand.DemandRecordMapper;
import com.toycloud.system.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * demandLogService业务层处理
 *
 * @author binlu6
 * @date 2024-11-06
 */
@RequiredArgsConstructor
@Service
public class DemandLogServiceImpl implements IDemandLogService {

    private final DemandLogMapper baseMapper;

    private final DemandRecordMapper recordMapper;

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RemoteSsoService remoteSsoService;

    public static final String APPID = "wdiON2lqQGqMjBHA70Rce";

    /**
     * 查询demandLog
     */
    @Override
    public DemandLogVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询demandLog列表
     */
    @Override
    public TableDataInfo<DemandLogVo> queryPageList(DemandLogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DemandLog> lqw = buildQueryWrapper(bo);
        Page<DemandLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询demandLog列表
     */
    @Override
    public List<DemandLogVo> queryList(DemandLogBo bo) {
        LambdaQueryWrapper<DemandLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<DemandLogVo> queryListBydid(Integer did) {
        DemandLogBo bo = new DemandLogBo();
        bo.setDid(did);
        LambdaQueryWrapper<DemandLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DemandLog> buildQueryWrapper(DemandLogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DemandLog> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getDid() != null, DemandLog::getDid, bo.getDid());
        lqw.eq(StringUtils.isNotBlank(bo.getVersion()), DemandLog::getVersion, bo.getVersion());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), DemandLog::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getProductType()), DemandLog::getProductType, bo.getProductType());
        lqw.eq(StringUtils.isNotBlank(bo.getFlag()), DemandLog::getFlag, bo.getFlag());
        lqw.eq(bo.getCreateDate() != null, DemandLog::getCreateDate, bo.getCreateDate());
        lqw.orderByDesc(DemandLog::getCreateTime);
        return lqw;
    }

    /**
     * 新增demandLog
     */
    @Override
    public Integer insertByBo(DemandLogBo bo) {
        DemandLog add = BeanUtil.toBean(bo, DemandLog.class);
        add.setCreateDate(DateUtils.getNowDate());
        Integer changeNewId;
        if("1".equals(add.getType())){
            changeNewId = changeById(add.getDid(),bo.getVersion());
            add.setVersion(StringUtils.incrementVersion(bo.getVersion()));
            add.setProductType("5");
        }else{
            changeNewId =bo.getDid();
        }
        add.setFlag("0");
        validEntityBeforeSave(add);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        add.setCreateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return changeNewId;
    }

    public Integer changeById(Integer id,String Version) {
        boolean flag =recordMapper.updateByPrimaryKey(id)>0;
        DemandRecordVo changeVo = recordMapper.selectVoById(id);
        DemandRecord demandRecord = recordMapper.selectById(id);
        DemandRecordBo bo = new DemandRecordBo();
        bo.setDemandVersion(StringUtils.incrementVersion(Version));
        bo.setDemandId(changeVo.getId());
        bo.setDemandContent(changeVo.getDemandContent());
        bo.setDemandTitle(changeVo.getDemandTitle());
        bo.setEnterFile(changeVo.getEnterFile());
        bo.setDemandResource(changeVo.getDemandResource());
        bo.setDemandType(changeVo.getDemandType());
        bo.setDemandPerson(changeVo.getDemandPerson());
        bo.setProposeTime(changeVo.getProposeTime());
        bo.setApplicationLabel(changeVo.getApplicationLabel());
        bo.setCategoryLabel(changeVo.getCategoryLabel());
        bo.setModelLabel(changeVo.getModelLabel());
        bo.setAppApply(changeVo.getAppApply());
        bo.setAppVersion(changeVo.getAppVersion());
        bo.setVersionCategory(changeVo.getVersionCategory());
        bo.setVersionModel(changeVo.getVersionModel());
        bo.setVersionModelVersion(changeVo.getVersionModelVersion());
        bo.setCategoryModelVersion(demandRecord.getCategoryModelVersion());
        bo.setApplyVersion(changeVo.getApplyVersion());
        bo.setFilterStatus("0");
        Integer newDemandId =this.copyByBo(bo);
        return newDemandId;
    }

    public Integer copyByBo(DemandRecordBo bo) {
        DemandRecord add = BeanUtil.toBean(bo, DemandRecord.class);
        add.setNowStatus("1");
        if(bo.getFilterStatus().equals("1")){
            add.setNowStatus("2");
            if(bo.getSurveyStatus().equals("1")){
                add.setNowStatus("3");
                if(bo.getAnalysisStatus().equals("1")){
                    add.setNowStatus("4");
                    if(bo.getReviewStatus().equals("1")){
                        add.setNowStatus("5");
                        if(bo.getDesignStatus().equals("1")){
                            add.setNowStatus("6");
                            if(bo.getDevelopStatus().equals("1")){
                                add.setNowStatus("7");
                                if(bo.getReleaseStatus().equals("1")){
                                    add.setNowStatus("8");
                                }
                            }
                        }
                    }
                }
            }
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        add.setCreateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
        boolean flag = recordMapper.insert(add) > 0;
        Integer id =null;
        if(flag){
            id =add.getId();
        }

        return id;
    }

    /**
     * 修改demandLog
     */
    @Override
    public Boolean updateByBo(DemandLogBo bo) {
        DemandLog update = BeanUtil.toBean(bo, DemandLog.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DemandLog entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除demandLog
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public String plusVersion(String version) {
        String newVersion ;
        newVersion = StringUtils.incrementVersion(version);
        return newVersion;
    }

    @Override
    public UserParam username(HttpServletRequest request) {
        String authorizationHeader = request.getHeader("Authortoken");
        String loginUser = jwtUtil.extractUsername(authorizationHeader);
        Object o = remoteSsoService.getUserInfo(APPID, loginUser);
        UserParam userParam = new UserParam();
        if (o instanceof Map) {
            Map<String, Object> resultMap = (Map<String, Object>) o;
            if ((int) resultMap.get("code") == 200) {
                Map<String, Object> userInfoMap = (Map<String, Object>) resultMap.get("data");
                userParam.setUserid((String) userInfoMap.get("userid"));
                userParam.setUsername((String) userInfoMap.get("username"));
            }
        }
        return userParam;
    }
}
